package com.翻转单词顺序;

import java.util.Arrays;

public class Solution {
    public String ReverseSentence(String str) {
        if(str.length()<=1)return str;
        //第一步将整个字符串翻转
        char[] array = str.toCharArray();
        Reserve(array,0,str.length());
        
        //第二步开始遍历寻找每个子单词的起始和结束位置，以空格为标准
        
        int start=0;
        int end=0;
        for(int i=0;i<str.length();i++){
            if(array[i]==' '){    
            	end=i-1;
            	
                int len=end-start+1;
                
                Reserve(array,start,end-start+1);
                
                start=i+1;
            }
             if(i==str.length()-1){
                end=i;
                Reserve(array,start,end-start+1);
            }
            
        }
        
        String res = new String(array);
        return res;
    }
    public void Reserve(char[] array,int index,int len){
        if(len<=1)return ;
        int end=index+len-1;
        while(index<end) {
        	char t = array[index];
        	array[index]=array[end];
        	array[end]=t;
        	index++;
        	end--;
        }
        return;
    }
}
